#include "ThreadPool.h"
#include <iostream>
#include <unistd.h>
using std::cout;
using std::endl;

ThreadPool::ThreadPool(size_t threadNum, size_t queueSize)
    : _threadNum(threadNum),
      _queueSize(queueSize),
      _taskQue(queueSize),
      _isExit(false)
{
    _threads.reserve(_threadNum);
}

ThreadPool::~ThreadPool()
{
}

void ThreadPool::start()
{
    for (size_t i = 0; i < _threadNum; ++i)
    {
        _threads.emplace_back(&ThreadPool::doTask,this);
    }
}

void ThreadPool::stop()
{
    while(!_taskQue.isEmpty()){
        sleep(1);
    }
    _isExit = true;
    _taskQue.wakeup();
    for (auto &th : _threads)
    {
        th.join();
    }
}

void ThreadPool::addTask(TASK task)
{
    if (task)
    {
        _taskQue.push(task);
    }
    else{
        cout<<"ptask = nullptr"<<endl;
    }
}

void ThreadPool::doTask()
{
    while (!_isExit)
    {
        TASK task = getTask();
        if (task)
        {
            task();
        }
    }
}

TASK ThreadPool::getTask()
{
    return _taskQue.pop();
}
